import React from "react";
import {DeviceEventEmitter, Platform, StyleSheet, TouchableOpacity, View} from "react-native";
import {echatIMSDK, EChatIMSDK} from "../../libs/sdk/echatim/core/sdk/EChatIMSDK";
import {
    FileInfo,
    FileUploadConfig,
    FileUploadListener,
    IFileServerClient,
    UploadError
} from "../../libs/sdk/echatim/core/fileclient/FileServerClient";
import Beans from "../../libs/sdk/echatim/common/utils";
import UUID from "../../libs/sdk/echatim/common/UUID";
import FileHelper from "../../libs/utils/FileHelper";
import EButton from "../utils/EButton";
import {BroadcastEvent} from "../../events/BroadcastEvent";


type UploadImagePropTypes = {
    component?:any,
    onStartUpload?:(info:FileInfo)=>void
    onUploading?:(info:FileInfo)=>void
    onUploaded:(info:FileInfo)=>void
}

type UploadImageStateTypes = {

}

export default class UploadFileComponent extends React.Component<UploadImagePropTypes, UploadImageStateTypes> {
    private htmlDomId:string = "";
    private fileClient:IFileServerClient|any;

    private fileUploadListener:FileUploadListener|any;

    constructor(props:UploadImagePropTypes, context:any) {
        super(props, context);
        this.htmlDomId = 'uploadImage-' + UUID.gen();

        const self = this;
        this.fileUploadListener = new class implements FileUploadListener {
            beforeUploadCallback= (info: FileInfo) => {
                if(self.props.onStartUpload){
                    self.props.onStartUpload(info);
                }
                DeviceEventEmitter.emit(BroadcastEvent.EVENT_FILE_UPLOAD_START, info);
                return info;
            };
            errorCallback = (info: (FileInfo | undefined), error: UploadError) => {
                console.error('errorCallback:' + Beans.json(error));
            };
            progressCallback =  (info: FileInfo) => {
                console.info(`file:${info.originFileName} uploaded:${info.uploadPercent}%`);
                DeviceEventEmitter.emit(BroadcastEvent.EVENT_FILE_UPLOADING, info);
            };
            uploadedCallback = (info: FileInfo) => {
                // console.info('uploadedCallback:' + Beans.json(info));
                // window.open(info.url);
                DeviceEventEmitter.emit(BroadcastEvent.EVENT_FILE_UPLOADED, info);
                self.props.onUploaded(info);
            };
        };
    }

    onComponentBind(im:EChatIMSDK){
        const self = this;
        const uploadConfig = new FileUploadConfig();
        uploadConfig.domId = this.htmlDomId;
        uploadConfig.type = '';

        im.newFileClient().init(uploadConfig, self.fileUploadListener);
    }


    onUploaderInit(im:EChatIMSDK){
        console.log('onUploaderInit');

        const self = this;
        const uploadConfig = new FileUploadConfig();
        uploadConfig.type = '';
        this.fileClient = im.newFileClient();
        this.fileClient.init(uploadConfig, self.fileUploadListener);
    }

    onUploaderSelectFile(){
        console.log('onUploaderSelectFile');
        FileHelper.select().then((filePath)=>{
            this.fileClient.upload(filePath);// 上传文件
        }).catch((e)=>{
        });

    }

    componentDidMount(): void {
        const im = echatIMSDK;
        console.log('UploadFileComponent componentDidMount sdk status:' + im.logined);
        if(!im || !im.logined){
            return;
        }
        if(Platform.OS === 'web'){
            this.onComponentBind(im);
        }
        else if(Platform.OS === 'android' || Platform.OS === 'ios'){
            this.onUploaderInit(im);
        }

    }

    render() {
        const clickComponent = this.props.component ? this.props.component : <EButton title={'上传'} onPress={()=>{this.onUploaderSelectFile()}}/>;

        return (
            <TouchableOpacity activeOpacity={0.5}
                              onPress={()=>{this.onUploaderSelectFile()}}
                              onPressIn={()=>{}}
                              onPressOut={()=>{}}
                              onLongPress={()=>{}}>
                <View nativeID={this.htmlDomId}>
                    {clickComponent}
                </View>
            </TouchableOpacity>
        );
    }
}

let styles = StyleSheet.create({
    container: {
    },
});
